﻿using IP2Region.Net.Abstractions;
using IP2Region.Net.XDB;

namespace TianYu.Core.Common
{
    public static class IPUtils
    {
        private static readonly ISearcher _searcher = null;
        static IPUtils()
        {
            var dbPath = Path.Combine(AppContext.BaseDirectory, "Data", "ip2region.xdb");
            _searcher = new Searcher(CachePolicy.Content, dbPath);
        }
        public static string IPToAddress(this string @this)
        {
            string addrStr = "未知";
            try
            {
                //有效的IPv4地址
                if (RegexUtils.IsIPAddress(@this))
                {
                    var ipInfo = _searcher.Search(@this);
                    if (!string.IsNullOrWhiteSpace(ipInfo))
                    {
                        var arr = ipInfo.Split('|', StringSplitOptions.RemoveEmptyEntries).Where(a => a != "0");
                        if (arr.Count() > 0)
                        {
                            addrStr = string.Join(",", arr);
                        }
                    }
                }
            }
            catch (Exception) { }

            return addrStr;
        }

    }
}
